import re
from flask import Blueprint,request,jsonify
import json
from db import db1

bp_good = Blueprint('goods',__name__)

@bp_good.route('goodM',methods=['POST','GET'])
def goodM():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "insert into goods values(0,'%s',%d)"%(data['name'],int(data['cid']))
        db1.insert(sql)

        return jsonify({'code':200})

    else:
        page = int(request.args.get('page'))
        size = int(request.args.get('size'))
        start = (page-1)*size
        cid = int(request.args.get('cid'))
        if cid>0:
             sql = "select g.id,g.name,g.cid,c.name as cname from goods as g left join cate as c on g.cid=c.id where g.cid=%d order by id desc limit %d,%d"%(cid,start,size)
             #查询总条数
             tsql = "select count(id) from goods where cid=%d"%(cid)
        else:
            sql = "select g.id,g.name,g.cid,c.name as cname from goods as g left join cate as c on g.cid=c.id order by id desc limit %d,%d"%(start,size)
            #查询总条数
            tsql = "select count(id) from goods"
        res = db1.findall(sql)
        total = db1.findone(tsql)
        return jsonify({"code":200,'list':res,'total':total['count(id)']})